package com.avertymaroc.users;

import static com.avertymaroc.library.C.TAG_SUCCESS;
import static com.avertymaroc.library.C.site_url;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.avertymaroc.app.MainActivity;
import com.avertymaroc.app.R;
import com.avertymaroc.beans.SondageRapide;
import com.avertymaroc.beans.User;
import com.avertymaroc.library.C;
import com.avertymaroc.library.HttpManager;
import com.avertymaroc.library.MyAdapter;
import com.avertymaroc.library.SessionManager;

public class SondagesRapides extends SherlockActivity{
	
	public static final String TAG_SONDAGES				= "sondages";
	public static final String KEY_SONDAGE				= "sondage";
	public static final String KEY_JOURS 				= "jours";
	public static final String KEY_HOURS 				= "hours";
	public static final String KEY_MIN 					= "minutes";
	public static final String KEY_SEC					= "secondes";
	public static final String KEY_TOTAL				= "total";
	public static final String KEY_PAGE					= "page";
	public static final int RC_VOTER					= 105;
	public static final String TAG_SONDAGE_SAVE 		= "saved_sondage";
	public static final String TAG_NUM_SONDAGE_RAPIDE 	= "nbre_sondage_rapide";
	public static final String TAG_SCROLLX				= "crollx";
	public static final String TAG_SCROLLY				= "scrolly";
	
	
	private ListView list_sr;
	private int _page = 0;
	private View footerView;
	private boolean loading = false;
	private String _url = site_url("mobile/sondages/index/") , _url_img = C.base_url("upload/user_images/temp/original/");
	MyAdapter mAdapter;
	private int total = 0;
	
	ArrayList<HashMap<String, Object>> sond_rap_list = new ArrayList<HashMap<String,Object>>();
	 HashMap<String, Object> map;

	private List<SondageRapide> listSondRaps = new ArrayList<SondageRapide>();
	private ImageButton logOut;
	private ImageButton homePage;
	private Listener l;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(MainActivity.THEME);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sondages_rapides);
		
		this.list_sr = (ListView) findViewById(R.id.list_sondages_rap);
		footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
		this.list_sr.addFooterView(footerView);
		
		 l = new Listener();
		initActionBarButtons();
		
		if(savedInstanceState == null)
		{
			init();
		}
		else
		{
			
			int i =0;
			_page = savedInstanceState.getInt(KEY_PAGE);
			total = savedInstanceState.getInt(KEY_TOTAL);

			while( i < savedInstanceState.getInt(TAG_NUM_SONDAGE_RAPIDE))
			{
				SondageRapide s = (SondageRapide) savedInstanceState.getSerializable(TAG_SONDAGE_SAVE+"_"+i);
				i++;
				listSondRaps.add(s);
				map = new HashMap<String, Object>();
				
				map.put(SondageRapide.KEY_TITRE , s.getTitre() );
				map.put(User.KEY_PRENOM, s.getUser().getPrenom()); 
				map.put(SondageRapide.KEY_VOTES,""+s.getVotes());
				
				map.put(User.KEY_IMAGE, _url_img+s.getUser().getImg());
				
				
					Map<String, Integer> delai = duree(s.getDuree(), s.getCurrent());
					if( delai != null){
						
						String t = "";
						t +=(delai.get(KEY_JOURS) != 0) ? delai.get(KEY_JOURS)+" jours  " : "" ;	
						t +=(delai.get(KEY_HOURS) != 0) ? delai.get(KEY_HOURS)+":" :"" ;
						t +=(delai.get(KEY_MIN) != 0) ? delai.get(KEY_MIN)+":" :"" ;
						t +=(delai.get(KEY_SEC) != 0) ? delai.get(KEY_SEC) :"" ;
						
						map.put(SondageRapide.KEY_DUREE, t);
						
					}else{
						map.put(SondageRapide.KEY_DUREE, stringRes(R.string.termine));
					}

				sond_rap_list.add(map);
				
			}
			 mAdapter = new MyAdapter(SondagesRapides.this, sond_rap_list);
			 list_sr.setAdapter(mAdapter);
			 list_sr.scrollTo(savedInstanceState.getInt(TAG_SCROLLX) , savedInstanceState.getInt(TAG_SCROLLY) );
			 list_sr.setOnScrollListener(l );
			 list_sr.setOnItemClickListener(l);
		}
		
		

		
		
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		int i = 0;
		for(SondageRapide s : listSondRaps){
			outState.putSerializable(TAG_SONDAGE_SAVE+"_"+i, s);
			i++;
		}
		outState.putInt(TAG_NUM_SONDAGE_RAPIDE , listSondRaps.size());
		outState.putInt(TAG_SCROLLX, list_sr.getScrollX());
		outState.putInt(TAG_SCROLLY , list_sr.getScrollY());
		outState.putInt(KEY_PAGE, _page);
		outState.putInt(KEY_TOTAL, total);

		super.onSaveInstanceState(outState);
	}
	
	
	void init(){
		HttpManager  httpManager = new HttpManager(SondagesRapides.this) {
			
			@Override
			protected void onPostExecute(String file_url) {
			
				getpDialog().dismiss();
				JSONObject res = getResult();
				
				try {
					int succes = res.getInt(TAG_SUCCESS);
					total = res.getInt(KEY_TOTAL);
						if(succes == 1){
							listSondRaps = conversion( res.getJSONArray(TAG_SONDAGES) );
							
							for(SondageRapide  s : listSondRaps){
								map = new HashMap<String, Object>();
								
								map.put(SondageRapide.KEY_TITRE , s.getTitre() );
								map.put(User.KEY_PRENOM, s.getUser().getPrenom()); 
								map.put(SondageRapide.KEY_VOTES,""+s.getVotes());
								
								map.put(User.KEY_IMAGE, _url_img+s.getUser().getImg());
								
								
									Map<String, Integer> delai = duree(s.getDuree(), s.getCurrent());
									if( delai != null){
										
										String t = "";
										t +=(delai.get(KEY_JOURS) != 0) ? delai.get(KEY_JOURS)+" jours  " : "" ;	
										t +=(delai.get(KEY_HOURS) != 0) ? delai.get(KEY_HOURS)+":" :"" ;
										t +=(delai.get(KEY_MIN) != 0) ? delai.get(KEY_MIN)+":" :"" ;
										t +=(delai.get(KEY_SEC) != 0) ? delai.get(KEY_SEC) :"" ;
										
										map.put(SondageRapide.KEY_DUREE, t);
										
									}else{
										map.put(SondageRapide.KEY_DUREE, stringRes(R.string.termine));
									}
									
									
								 

								sond_rap_list.add(map);
							   
							}
							
							 mAdapter = new MyAdapter(SondagesRapides.this, sond_rap_list);
							 list_sr.setAdapter(mAdapter);
							 list_sr.setOnScrollListener(new Listener() );
						}
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(), "Erreur parsing data : " + e.getMessage(), Toast.LENGTH_LONG).show();
				}
				
			}}; 
			
			
		_url +=new SessionManager(getApplicationContext()).getUserDetails().getId()+"/"+_page;
		httpManager.setUrl(_url)
				   .execute();
		
		
		list_sr.setOnItemClickListener(l);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		Log.d("Activity result" , "requestCode = "+requestCode+"  resuktCode = "+resultCode);
		if(requestCode == RC_VOTER)
			if(resultCode == SondageRapDetails.RES_CODE){
				int pos = data.getIntExtra(SondageRapDetails.KEY_POISTION, -1);
				if(pos != -1){
					Log.d("Activity result" , "pos = "+pos);
					listSondRaps.get(pos).setShow_resultats(true);
					listSondRaps.get(pos).setVotes( listSondRaps.get(pos).getVotes() + 1);
				}
				
			}
			
		
	};
	
	 Map<String,	Integer> duree(Date dateFin , Date current){

		 Map<String, Integer> duree = null ;
		if(dateFin.getTime() > current.getTime()){
			int j , h , m , s;
			duree = new HashMap<String, Integer>();
			
			Long def = (dateFin.getTime() - current.getTime())/1000;
			j = (int) (def / (60*60*24));
			def =  def % ( 24*60*60 );
			h = (int) (def / (60*60));
			def = def %( 60*60 );
			m = (int) (def / 60);
			def = def % 60;
			s = (int) (def / 1);

			
			duree.put(KEY_JOURS , j);
			duree.put(KEY_HOURS , h);
			duree.put(KEY_MIN , m);
			duree.put(KEY_SEC , s);
		}
		
		return duree;
	}
	 
		private String stringRes(int resId) {
			return getResources().getString(resId);
		}
private List<SondageRapide> conversion(JSONArray sondag){
	
	List<SondageRapide> listSond = new ArrayList<SondageRapide>();
		try {

			for(int i = 0 ; i < sondag.length() ;i++){
				listSond.add(new SondageRapide( sondag.getJSONObject(i) ) );
				
				}
			
		} catch (JSONException e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
		 catch (ParseException e) {
			 Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
			}
		return listSond;
	
}



protected boolean load(int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
	boolean lastItem = firstVisibleItem + visibleItemCount == totalItemCount && list_sr.getChildAt(visibleItemCount -1) != null && list_sr.getChildAt(visibleItemCount-1).getBottom() <= list_sr.getHeight();
	boolean moreRows = list_sr.getAdapter().getCount() <  total;
	return moreRows && lastItem && !loading;
	
}
private void loadNextPage(){
	
HttpManager  httpManager = new HttpManager(SondagesRapides.this) {
		@Override
		protected void onPostExecute(String file_url) {
			sond_rap_list = new ArrayList<HashMap<String,Object>>();
			JSONObject res = getResult();
			
			try {
				int succes = res.getInt(TAG_SUCCESS);
					if(succes == 1){
						List<SondageRapide> l = conversion( res.getJSONArray(TAG_SONDAGES) );
						
						
						for(SondageRapide  s: l){
							listSondRaps.add(s);
							map = new HashMap<String, Object>();
							
							map.put(SondageRapide.KEY_TITRE , s.getTitre() );
							map.put(User.KEY_PRENOM, s.getUser().getPrenom()); 
							map.put(SondageRapide.KEY_VOTES,""+s.getVotes());
							
							map.put(User.KEY_IMAGE, _url_img+s.getUser().getImg());
							
							
								Map<String, Integer> delai = duree(s.getDuree(), s.getCurrent());
								if( delai != null){
									
									String t = "";
									t +=(delai.get(KEY_JOURS) != 0) ? delai.get(KEY_JOURS)+" jours  " : "" ;	
									t +=(delai.get(KEY_HOURS) != 0) ? delai.get(KEY_HOURS)+":" :"" ;
									t +=(delai.get(KEY_MIN) != 0) ? delai.get(KEY_MIN)+":" :"" ;
									t +=(delai.get(KEY_SEC) != 0) ? delai.get(KEY_SEC) :"" ;
									
									map.put(SondageRapide.KEY_DUREE, t);
									
								}else{
									map.put(SondageRapide.KEY_DUREE, stringRes(R.string.termine));
								}
								
							sond_rap_list.add(map);
						}
						mAdapter.addData(sond_rap_list);
						mAdapter.notifyDataSetChanged();
						list_sr.removeFooterView(footerView);
						loading = false;
					}
			} catch (JSONException e) {
				Toast.makeText(getApplicationContext(), "Erreur parsing data : " + e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
		}}; 
		
		
		
	_url =site_url("mobile/sondages/index/") + (new SessionManager(getApplicationContext()).getUserDetails().getId() )+"/"+(++_page);
	httpManager.setUrl(_url)
				.setpDialog(null)
			   .execute();
}
class Listener implements OnScrollListener, OnItemClickListener{

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (load(firstVisibleItem, visibleItemCount, totalItemCount))
		{
			loading = true;
			list_sr.addFooterView(footerView, null, false);
			loadNextPage();
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position,
			long id) {
			
			Intent i = new Intent(SondagesRapides.this , SondageRapDetails.class);

			i.putExtra(KEY_SONDAGE,listSondRaps.get(position ));
			i.putExtra("position",position);
			
			startActivityForResult(i, RC_VOTER);
			
	}
	
}


private void initActionBarButtons(){
	 
	 logOut = (ImageButton) findViewById(R.id.ab_right_button);
	 homePage = (ImageButton) findViewById(R.id.ab_left_button);
	 
	 logOut.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			new SessionManager(getApplicationContext()).logoutUser();
			
		}
	});
	 homePage.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
		
			finish();
			
		}
	});
	 
}


   
}
